from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 加载数据并提取前两个特征
ds = load_iris()
x, y = ds.data[:, 0:2], ds.target  # 仅使用萼片长度和萼片宽度两个特征
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, test_size=50)

# 打印数据基本信息
print(f"x shape: {x.shape}, y shape: {y.shape}")
print(f"x_1： 最小值{x[:, 0].min():.2f}，最大值{x[:, 0].max():.2f}，均值{x[:, 0].mean():.2f}，个数{x[:, 0].shape[0]}")
print(f"x_2： 最小值{x[:, 1].min():.2f}，最大值{x[:, 1].max():.2f}，均值{x[:, 1].mean():.2f}，个数{x[:, 1].shape[0]}")
print(f"x_train shape: {x_train.shape}, y_train shape: {y_train.shape}")
print(f"x_test shape: {x_test.shape}, y_test shape: {y_test.shape}")


from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 训练逻辑回归模型
model = LogisticRegression()
model.fit(x_train, y_train)

# 评估模型准确率
mc = model.score(x_test, y_test)
ac = accuracy_score(y_test, model.predict(x_test))
print(f"模型预测准确率（Score）：{mc:.4f}")
print(f"模型预测准确率（Accuracy）：{ac:.4f}")


# 导入可视化库
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

# 绘制分类决策边界
N, M = 500, 500  # 网格采样点数量
t1 = np.linspace(4, 8, N)  # 萼片长度的采样范围
t2 = np.linspace(1.5, 5, M) # 萼片宽度的采样范围
print(f"t1： 最小值{t1.min():.2f}，最大值{t1.max():.2f}，均值{t1.mean():.2f}，个数{t1.shape[0]}")
print(f"t2： 最小值{t2.min():.2f}，最大值{t2.max():.2f}，均值{t2.mean():.2f}，个数{t2.shape[0]}")

x1, x2 = np.meshgrid(t1, t2)  # 生成网格点
x_new = np.stack((x1.flat, x2.flat), axis=1)  # 转换为模型可预测的格式
y_predict = model.predict(x_new)  # 预测网格点类别
y_hat = y_predict.reshape(x1.shape)  # 重塑为网格形状


# 设置颜色映射并绘制决策边界
iris_cmap = ListedColormap(["#ACC6C0", "#FF8080", "#A0A0FF"])
plt.pcolormesh(x1, x2, y_hat, cmap=iris_cmap, alpha=0.5)  # alpha设置透明度

# 绘制样本点
plt.scatter(x[y == 0, 0], x[y == 0, 1], s=30, c="g", marker="^", label="山鸢尾（类别0）")
plt.scatter(x[y == 1, 0], x[y == 1, 1], s=30, c="r", marker="o", label="变色鸢尾（类别1）")
plt.scatter(x[y == 2, 0], x[y == 2, 1], s=30, c="b", marker="s", label="维吉尼亚鸢尾（类别2）")

# 设置图形属性
plt.rcParams["font.sans-serif"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]  # 支持中文显示
plt.xlabel("萼片长度（cm）")
plt.ylabel("萼片宽度（cm）")
plt.title("逻辑回归分类决策边界（仅使用前两个特征）")
plt.legend()
plt.show()